<?php

class generalFunction {

    public function getCurrentScriptName() {
	$scriptArray = explode('/', $_SERVER['SCRIPT_NAME']);
	if (count($scriptArray) > 0) {
	    $script_name = end($scriptArray);
	    return $script_name;
	}
	return '';
    }

    public function detect_mobile() {
	if (preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipaq|ipod|j2me|java|midp|mini|mmp|motorola|nec-|nokia|palm|panasonic|philips|phone|playbook|sagem|sharp|sie-|silk|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT'])) {
	    return "MOBILE";
	} else if (preg_match('/(ipad)/i', $_SERVER['HTTP_USER_AGENT'])) {
	    return "IPAD";
	} else {
	    return "BROWSER";
	}
    }

    public function navigationSelector($currentScriptArray = Array()) {
	if (in_array($this->getCurrentScriptName(), $currentScriptArray)) {
	    return true;
	}
	return false;
    }

    public function allowedImageFormats() {
	$imageAllowedFormat = Array(
	    "image/gif",
	    "image/pjpeg",
	    "image/jpeg",
	    "image/jpg",
	    "image/png",
	    "image/x-png",
	    "image/gif"
	);
	return $imageAllowedFormat;
    }
	
	
	function scanDir($directory, $empty=FALSE) {
	// if the path has a slash at the end we remove it here
	if (substr($directory, -1) == '/') {
		$directory = substr($directory, 0, -1);
	}

	// if the path is not valid or is not a directory ...
	if (!file_exists($directory) || !is_dir($directory)) {
		// ... we return false and exit the function
		return FALSE;
		// ... if the path is not readable
	} elseif (!is_readable($directory)) {
		// ... we return false and exit the function
		return FALSE;
		// ... else if the path is readable
	} else {
		// we open the directory
		$handle = opendir($directory);
		// and scan through the items inside
		while (FALSE !== ($item = readdir($handle))) {
			// if the filepointer is not the current directory
			// or the parent directory
			if ($item != '.' && $item != '..') {
				// we build the new path to delete
				$path = $directory . '/' . $item;
				// if the new path is a directory
				if (is_dir($path)) {
					// we call this function with the new path
					$this->scanDir($path);
				// if the new path is a file
				} else {
				// we remove the file
					unlink($path);
				}
			}
		}
		// close the directory
		closedir($handle);

		// if the option to empty is not set to true
		if ($empty == FALSE) {
			// try to delete the now empty directory
			if (!rmdir($directory)) {
				// return false if not possible
				return FALSE;
			}
		}
		// return success
		return TRUE;
	}
}
	
    public function image_validate($imageAllowedFormat, $image = 'image') {
	if (!$_FILES) {
	    return false;
	}
	
	if (count($_FILES[$image]['name']) == 1) {
	    if (!in_array($_FILES[$image]['type'], $imageAllowedFormat)) {
		return 'IMPROPER_FORMAT';
	    }
	    $image_array_size = Array();
	    $image_array_size = getimagesize($_FILES[$image]['tmp_name']);
	    $image_height = $image_array_size['0'];
	    $image_width = $image_array_size['1'];
	} else {
	    foreach ($_FILES[$image]['name'] as $key => $value) {
		if ($_FILES[$image]['tmp_name'][$key] == '') {
		    return 'UN_UPLOADED';
		}
		if (!in_array($_FILES[$image]['type'][$key], $imageAllowedFormat)) {
		    return 'IMPROPER_FORMAT';
		}
	    }
	}
	return 'OK';
    }

    public function file_validate($allowedFileFormat, $document = 'document') {
	if (!$_FILES) {
	    return false;
	}
	if (count($_FILES[$document]['name']) == 1) {
	    if (!in_array($_FILES[$document]['type'], $allowedFileFormat)) {
		return 'IMPROPER_FORMAT';
	    }
	} else {
	    foreach ($_FILES[$document]['name'] as $key => $value) {
		if ($_FILES[$document]['tmp_name'][$key] == '') {
		    return 'UN_UPLOADED';
		}
		if (!in_array($_FILES[$document]['type'][$key], $allowedFileFormat)) {
		    return 'IMPROPER_FORMAT';
		}
	    }
	}
	return 'OK';
    }
	
    public function searchfilter($searchString) {
	$search_array = Array('%', '_');
	$replace_array = Array('\%', '\_');
	return str_replace($search_array, $replace_array, $searchString);
    }

    public function cleanfilter($searchString) {
	$search_array = Array('\%', '\_');
	$replace_array = Array('%', '_');
	return str_replace($search_array, $replace_array, $searchString);
    }

    public function filter($array = '', $filterArray = Array()) {
	/*
	  for the filter array the value with  following key will call following functionms
	  mysqlRealEscape => mysql_real_escape_string
	  htmlEntityDecode => html_entity_decode
	  htmlEntity => htmlentities
	  trim => TrimElement
	  stripslashes => StripSlashElement
	 */
	foreach ($filterArray as $filterType) {
	    if (is_array($array)) {
		$array = array_map($filterType, $array);
	    } else {
		$array = $filterType($array);
	    }
	}
	return $array;
    }

    public function redirect($url) {
	if ($url == '') {
	    echo "redirect url cannot be empty";
	    exit;
	}
	header('Location: ' . $url);
	exit;
    }


    public function ValidUrl($url) {
	$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
	$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
	$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
	$regex .= "(\:[0-9]{2,5})?"; // Port
	$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
	$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
	$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
	$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
	if (preg_match("/^$regex$/", $url)) {
	    return true;
	}
	return false;
    }

    public function ValidEmailAddress($EmailAddress) {
	if (!preg_match("/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i", $EmailAddress)) {
	    return false;
	}
	return true;
    }

    public function ValidAlphaNumeric($name) {
	if (!preg_match("/^[a-zA-Z0-9 _-]+$/", $name)) {
	    return false;
	}
	return true;
    }

    public function isNumeric($n) {
	if (!preg_match("/^[0-9]+$/", $n)) {
	    return false;
	}
	return true;
    }

    public function isFloat($string) {
	if (!preg_match("/^[0-9]+(.[0-9]+)?$/", $string)) {
	    return false;
	}
	return true;
    }

    public function ValidatePassword($Pwd) {
	if (strlen($Pwd) < 5) {
	    return false;
	}
	return true;
    }

    public function IsValidDate($str) {
	$stamp = strtotime($str);

	if (!is_numeric($stamp)) {
	    return FALSE;
	}
	$month = date('m', $stamp);
	$day = date('d', $stamp);
	$year = date('Y', $stamp);

	if (checkdate($month, $day, $year)) {
	    return TRUE;
	}

	return FALSE;
    }

    public function IsGreaterDate($date, $expiry_date) {
	$date = strtotime($date);
	$expiry_date = strtotime($expiry_date);
	if ($expiry_date > $date) {
	    return FALSE;
	}
	return TRUE;
    }

    public function IsEmpty($value='') {
	if (trim($value) == '') {
	    return true;
	}
	return false;
    }

}

function pr($array, $exit = false) {
    echo "<pre>";
    print_R($array);
    echo "</pre>";
    if ($exit) {
	exit;
    }
}

function mysqlRealEscape($str = '') {
    if ($str == '') {
	return;
    }
    return mysql_real_escape_string($str);
}

function htmlEntityDecode($str = '') {
    if ($str == '') {
	return;
    }
    return htmlspecialchars_decode($str, ENT_QUOTES);
}

function htmlEntity($str = '') {
    if ($str == '') {
	return;
    }
    return htmlspecialchars($str, ENT_QUOTES);
}

function utfencode($str = '') {
    if ($str == '') {
	return;
    }
    return utf8_encode($str);
}

function utfdecode($str = '') {
    if ($str == '') {
	return;
    }
    return utf8_decode($str);
}

function addslash($str = '') {
    if ($str == '') {
	return;
    }
    return addslashes($str);
}

function stripslash($str = '') {
    if ($str == '') {
	return;
    }
    return stripslashes($str);
}

function TrimElement($str = '') {
    if ($str == '') {
	return;
    }
    return trim($str);
}

function StripSlashElement($str = '') {
    if ($str == '') {
	return;
    }
    return stripslashes($str);
}

function recursivEncodeArray(&$array = array()) {

    foreach ($array as $key => $value) {
	if (is_array($value)) {
	    recursivEncodeArray($array[$key]);
	} else {
	    $array[$key] = utf8_decode($array[$key]);
	}
    }
}

function getCollapseText($_text, $_length=150) {
    if (strlen($_text) > $_length) {
	$_temp_text = substr($_text, 0, $_length);
	$_temp_text .="...";
	return $_temp_text;
    } else {
	return $_text;
    }
}
function dl_file($file) {

    //First, see if the file exists
    if (!is_file($file)) {
	die("<div style='text-align:center;'><h1> Sorry, file temporary not available!</h1></div>");
    }

    //Gather relevent info about file
    $len = filesize($file);
    $filename = basename($file);
    $file_extension = strtolower(substr(strrchr($filename, "."), 1));

    //This will set the Content-Type to the appropriate setting for the file
    switch ($file_extension) {
	case "pdf": $ctype = "application/pdf";
	    break;
	case "exe": $ctype = "application/octet-stream";
	    break;
	case "zip": $ctype = "application/zip";
	    break;
	case "doc": $ctype = "application/msword";
	    break;
	case "xls": $ctype = "application/vnd.ms-excel";
	    break;
	case "ppt": $ctype = "application/vnd.ms-powerpoint";
	    break;
	case "gif": $ctype = "image/gif";
	    break;
	case "png": $ctype = "image/png";
	    break;
	case "jpeg":
	case "jpg": $ctype = "image/jpg";
	    break;
	case "mp3": $ctype = "audio/mpeg";
	    break;
	case "wav": $ctype = "audio/x-wav";
	    break;
	case "mpeg":
	case "mpg":
	case "mpe": $ctype = "video/mpeg";
	    break;
	case "mov": $ctype = "video/quicktime";
	    break;
	case "avi": $ctype = "video/x-msvideo";
	    break;

	//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
	case "php":
	case "htm":
	case "html":
	case "txt": die("<b>Cannot be used for " . $file_extension . " files!</b>");
	    break;

	default: $ctype = "application/force-download";
    }

    //Begin writing headers
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");

    //Use the switch-generated Content-Type
    header("Content-Type: $ctype");

    //Force the download
    //$header="Content-Disposition: attachment; filename=".$filename.";"; //for force fully download
    $header = "Content-Disposition: inline; filename=" . $filename . ";";
    header($header);
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $len);
    @readfile($file);
    exit;
}

?>